import type { AIModel } from '../types/model'

const STORAGE_KEY = 'ai_models'

export const modelStorage = {
  getModels(): AIModel[] {
    const models = localStorage.getItem(STORAGE_KEY)
    return models ? JSON.parse(models) : []
  },

  saveModels(models: AIModel[]) {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(models))
  },

  addModel(model: Omit<AIModel, 'id'>) {
    const models = this.getModels()
    if (model.isDefault) {
      models.forEach(m => m.isDefault = false)
    }
    const newModel = {
      ...model,
      id: Date.now()
    }
    models.push(newModel)
    this.saveModels(models)
    return newModel
  },

  updateModel(model: AIModel) {
    const models = this.getModels()
    const index = models.findIndex(m => m.id === model.id)
    if (index !== -1) {
      if (model.isDefault) {
        models.forEach(m => m.isDefault = false)
      }
      models[index] = model
      this.saveModels(models)
    }
  },

  deleteModel(id: number) {
    const models = this.getModels()
    const newModels = models.filter(m => m.id !== id)
    this.saveModels(newModels)
  },

  setDefaultModel(id: number) {
    const models = this.getModels()
    models.forEach(m => m.isDefault = m.id === id)
    this.saveModels(models)
  },

  getDefaultModel(): AIModel | undefined {
    return this.getModels().find(m => m.isDefault)
  }
} 